package com.chtw.vuedemo.controller;

import com.chtw.vuedemo.bean.Brands;
import com.chtw.vuedemo.response.RespUtil;
import com.chtw.vuedemo.response.enumutil.CodeAndMsg;
import com.chtw.vuedemo.service.impl.BrandsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chtw
 * @date 2020-09-27 22:49
 */
@RestController
@RequestMapping("/brands")
public class BrandsController {

    @Autowired
    private BrandsServiceImpl brandsService;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public RespUtil<List<Brands>> getAllBrands() {
        try {
            List<Brands> data = brandsService.getAllBrands();
            return new RespUtil<>(CodeAndMsg.SUCCESS, data);
        } catch (Exception e) {
            return new RespUtil<>(CodeAndMsg.FAIL, null);
        }
    }

    @GetMapping(value = "/get/{id}")
    public RespUtil<Brands> getById(@PathVariable int id){
        try {
            Brands brands = brandsService.getById(id);
            return new RespUtil<>(CodeAndMsg.SUCCESS, brands);
        }catch (Exception e){
            return new RespUtil<>(CodeAndMsg.FAIL, null);
        }
    }

    @PostMapping(value = "/insert")
    public RespUtil<Boolean> insert(@RequestBody Brands brands){
        try{
            boolean inserted = brandsService.insert(brands);
            return new RespUtil<>(CodeAndMsg.SUCCESS, inserted);
        }catch (Exception e){
            return new RespUtil<>(CodeAndMsg.FAIL, null);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    public RespUtil<Boolean> delete(@PathVariable int id){
        try{
            boolean deleted = brandsService.delete(id);
            return new RespUtil<>(CodeAndMsg.SUCCESS, deleted);
        }catch (Exception e){
            return new RespUtil<>(CodeAndMsg.FAIL, null);
        }
    }

    @GetMapping(value = "/search")
    public RespUtil<List<Brands>> search(Brands brands){
        try{
            List<Brands> brandss = brandsService.search(brands);
            return new RespUtil<>(CodeAndMsg.SUCCESS, brandss);
        }catch (Exception e){
            return new RespUtil<>(CodeAndMsg.FAIL, null);
        }
    }
}
